package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) {
        //查询数据库是否存在注册的账号
        User temp = userMapper.selectByEamilAndPassword(user.getEmail(), null);
        //存在.抛出自定义异常
        if (temp != null) {
            throw new RuntimeException("该账号已存在,请重新注册!");
        }else{
            //不存在,进行注册
            //自动补全默认头像/背景/性别
            user.setHeadImgUrl("/upload/fd72cbec-2d41-4462-9287-fec93f12cc24.jpg");
            user.setCoverImgUrl("/upload/4341433b-d9e9-4474-880a-6799acd04b30.jpeg");
            user.setGender(User.gender_DEFAULT);
            userMapper.insert(user);
        }

    }

    @Override
    public User login(User user) {
        //查询数据库是否存在账号
        if (StringUtils.hasLength(user.getEmail()) && StringUtils.hasLength(user.getPassword())) {
            User temp = userMapper.selectByEamilAndPassword(user.getEmail(), user.getPassword());
            //不存在.抛出自定义异常
            if (temp == null) {
                throw new RuntimeException("账号密码不匹配,请重新登录!");
            }else{
                //存在,将登录用户存入session作用域
                UserContext.setCurrentUser(temp);
                return temp;
            }
        }
        throw new RuntimeException("账号密码不能为空,请重新登录!");
    }

    @Override
    public PageInfo<User> list(QueryObject qo) {
        //分页插件,增强紧跟的下一条查询语句
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<User> list = userMapper.selectForList(qo);
        return new PageInfo<User>(list);
    }

    @Override
    public void updateInfo(User user) {
        userMapper.updateByPrimaryKey(user);
    }
}
